package controller;



import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import service.RoomManageService;
import util.Utilities;
import dto.AddressDTO;
import dto.FileListDTO;
import dto.MemberDTO;
import dto.RoomDTO;
import dto.RoomDTO2;

@Controller
public class RoomController {
	private RoomManageService service;
	private String uploadDirectory;

	public RoomController(RoomManageService service, String uploadDirectory){
		this.service = service;
		this.uploadDirectory = uploadDirectory;
	}
	@RequestMapping("roominput.do")
	public ModelAndView roomBasicFormController(HttpSession session){
		if(session.getAttribute("login_info")==null){
			return new ModelAndView("login_form.jsp", "error_message", "로그인 후 객실을 등록해주세요");
		}
		return new ModelAndView("room_input_basic.jsp");
	}
	@RequestMapping("roominputbasic.do")
	public ModelAndView registerMemberBasic(HttpServletRequest request, HttpSession session, RoomDTO rdto){
		rdto.setPhone(request.getParameter("phone_1")+request.getParameter("phone_2")+request.getParameter("phone_3"));
		rdto.setAddressId(request.getParameter("seq"));	
		
		rdto.setMember((MemberDTO)session.getAttribute("login_info"));
		System.out.println("memberId:"+(MemberDTO)session.getAttribute("login_info"));
		System.out.println("basic : "+rdto);
		return new ModelAndView("room_input_add.jsp", "rdto", rdto);
	}
	@RequestMapping("roominputadd.do")
	public ModelAndView registerMemberAdd(RoomDTO rdto){
		System.out.println("add : "+rdto);
		return new ModelAndView("room_input_fileup.jsp", "rdto", rdto);
	}
	@RequestMapping("roominputfileup.do")
	public ModelAndView registerMemberFileup(HttpServletRequest request, RoomDTO rdto){
		System.out.println("fileup1 : "+rdto);	
		try{
			rdto.setProperty(service.searchPropertyId(request.getParameter("propertyId")));
			rdto.setPrivacy(service.searchPrivacyId(request.getParameter("privacyId")));
			rdto.setRefund(service.searchRefundId(request.getParameter("refundId")));
			rdto.setAddress(service.searchBySeq(request.getParameter("addressId")));
			HashMap map = new HashMap();
			System.out.println("fileup2 : "+rdto);
			System.out.println("controller : "+rdto.getRoomNo());
			map.put("rdto", rdto);
			service.registerRoom(rdto);
			List<MultipartFile> list = rdto.getUpfile();
			ArrayList<FileListDTO> flist = new ArrayList<FileListDTO>();
			for(MultipartFile file : list){
				if(!file.isEmpty()){
					String fileName = file.getOriginalFilename();
					String extension = fileName.substring(fileName.lastIndexOf("."));
					//파일명 중복방지처리
					long time = System.currentTimeMillis();
					int random = (int)(Math.random()*100)+1;
					String newFileName = time+random+extension;
					//파일 이동				
					file.transferTo(new File(uploadDirectory, newFileName));
					FileListDTO fdto = new FileListDTO();
					fdto.setFileName(newFileName);
					fdto.setRoomNo(rdto.getRoomNo());
					System.out.println("fileup3 : "+fdto);
					service.registerFile(fdto);		
					flist.add(fdto);
				}
			}	
			map.put("flist", flist);
			return new ModelAndView("room_input_success.res", map);
		}catch(SQLException e){
			e.printStackTrace();
			return new ModelAndView("error.res", "error_message", e.getMessage());
		}catch(IOException e){
			e.printStackTrace();
			return new ModelAndView("error.res", "error_message", e.getMessage());
		}
	}
	@RequestMapping("searchAddress.do")
	public ModelAndView searchAddress(HttpServletRequest request, HttpServletResponse response)throws Exception{
		try{
			String dong = request.getParameter("dong");
			ArrayList<AddressDTO> list = service.searchAddress(dong);
			return new ModelAndView("address_popup", "list", list);
		}catch(Exception e){
			e.printStackTrace();
			return new ModelAndView("error.res", "error_message", e.getMessage());
		}		
	}
	@RequestMapping("deleteRoom.do")
	public ModelAndView deleteRoom(int roomNo, String memberId){
		try{
			ArrayList<FileListDTO> flist = service.searchFileListByRoomNo(roomNo);			
			service.delete(roomNo);
			service.deleteRoom(roomNo);
			for(FileListDTO fdto : flist){
				File file = new File(uploadDirectory, fdto.getFileName());
				file.delete();
			}
			
			return selectByadmin(memberId);
		}catch(SQLException e){
			e.printStackTrace();
			return new ModelAndView("error.res", "error_message", e.getMessage());
		}	
	}
	@RequestMapping("allRoomList.do")
	public ModelAndView MyRoomList(){
		ModelAndView mv = null;
		try{
			ArrayList<RoomDTO2> list = service.allRoomList2();			
			System.out.println(list);			
			return new ModelAndView("allRoomlist.room_search", "list",list);
		} catch (Exception e) {
			e.printStackTrace();
			mv = new ModelAndView("error.res", "error_message", e.getMessage());
		}
		return mv;
	}
	@RequestMapping("myRoomList.do")
	public ModelAndView MyRoomList(String memberId){
		try{
			ArrayList<RoomDTO> rlist = service.searchMyRoomListByMemberId(memberId);			
			System.out.println("myroomlist : "+rlist);
			ArrayList<HashMap> list = new ArrayList<HashMap>();
			for(RoomDTO rdto : rlist){
				HashMap map = new HashMap();
				FileListDTO fdto = service.searchRoomFileByRoomNo(rdto.getRoomNo());
				map.put("rdto", rdto);
				map.put("fdto", fdto);
				list.add(map);				
			}
			return new ModelAndView("myRoomList.res", "list", list);
		}catch(SQLException e){
			e.printStackTrace();
			return new ModelAndView("error.res","error_message",e.getMessage());
		}	
	}
	@RequestMapping("roomDetail.do")
	public ModelAndView roomDetail(int roomNo){
		try{
			System.out.println("roomNo : "+roomNo);
			RoomDTO rdto = service.searchRoomDetailByRoomNo(roomNo);
			System.out.println("roomDetail.do : "+rdto);
			ArrayList<FileListDTO> flist = service.searchFileListByRoomNo(roomNo);
			HashMap map = new HashMap();
			map.put("rdto", rdto);
			map.put("flist", flist);
			return new ModelAndView("roomDetail.res", map);
		}catch(SQLException e){
			e.printStackTrace();
			return new ModelAndView("error.res", "error_message", e.getMessage());
		}		
	}
	@RequestMapping("modifymenu.do")
	public String modifyFormController(){
		return "modify_menu.jsp";
	}
	@RequestMapping("modifyMapping.do")
	public ModelAndView modifyRoomInfo(HttpServletRequest request){
		String comment = request.getParameter("comment");	
		try{
			int roomNo = Integer.parseInt(request.getParameter("roomNo"));			
			if(comment.equals("basic")){
				RoomDTO rdto = service.searchRoomDetailByRoomNo(roomNo);
				rdto.setDescription(Utilities.changeContentForTextArea(rdto.getDescription()));
				System.out.println("modifyMapping : "+rdto);
				return new ModelAndView("modify_room_info_basic.jsp", "rdto", rdto);
			}else if(comment.equals("add")){	
				RoomDTO rdto = service.searchRoomDetailByRoomNo(roomNo);
				return new ModelAndView("modify_room_info_add.jsp", "rdto", rdto);
			}else if(comment.equals("fileup")){	
				ArrayList<FileListDTO> flist = service.searchFileListByRoomNo(roomNo);
				return new ModelAndView("modify_room_info_fileup.jsp", "flist", flist);
			}
		}catch(SQLException e){
			e.printStackTrace();
			return new ModelAndView("error.res", "error_message", e.getMessage());
		}catch(NumberFormatException e){	
			e.printStackTrace();
			return new ModelAndView("error.res", "error_message", e.getMessage());
		}
		return new ModelAndView("error.res", "error_message", "comment값 없음");		
	}
	@RequestMapping("modifyroominputbasic.do")
	public ModelAndView modifyRoomInfoBasic(HttpServletRequest request, RoomDTO rdto){
		rdto.setPhone(request.getParameter("phone_1")+request.getParameter("phone_2")+request.getParameter("phone_3"));
		System.out.println("modify - seq : "+request.getParameter("seq"));
		rdto.setAddressId(request.getParameter("seq"));
		try{			
			service.modifyRoomInfoBasic(rdto);
			System.out.println("modifyroom_roomNo : "+rdto.getRoomNo());
			return roomDetail(rdto.getRoomNo());
		}catch(SQLException e){
			e.printStackTrace();
			return new ModelAndView("error.res", "error_message", e.getMessage());
		}
	}
	@RequestMapping("modifyroominputadd.do")
	public ModelAndView modifyRoomInfoAdd(HttpServletRequest request, RoomDTO rdto){
		try{
			service.modifyRoomInfoadd(rdto);
			System.out.println("modifyroom_roomNo : "+rdto.getRoomNo());
			return roomDetail(rdto.getRoomNo());
		}catch(SQLException e){
			e.printStackTrace();
			return new ModelAndView("error.res", "error_message", e.getMessage());
		}
	}
	@RequestMapping("modifyroominputfileup.do")
	public ModelAndView modifyRoomInfoFileup(HttpServletRequest request, RoomDTO rdto){		
		try{
			List<MultipartFile> list = rdto.getUpfile();
			for(MultipartFile file : list){
				if(!file.isEmpty()){
					String fileName = file.getOriginalFilename();
					String extension = fileName.substring(fileName.lastIndexOf("."));
					//파일명 중복방지처리
					long time = System.currentTimeMillis();
					int random = (int)(Math.random()*100)+1;
					String newFileName = time+random+extension;
					//파일 이동				
					file.transferTo(new File(uploadDirectory, newFileName));
					FileListDTO fdto = new FileListDTO();
					fdto.setFileName(newFileName);
					fdto.setRoomNo(rdto.getRoomNo());
					System.out.println("modifyfile : "+fdto);
					service.registerFile(fdto);
				}
			}	
			return roomDetail(rdto.getRoomNo());
		}catch(SQLException e){
			e.printStackTrace();
			return new ModelAndView("error.res", "error_message", e.getMessage());
		}catch(IOException e){
			e.printStackTrace();
			return new ModelAndView("error.res", "error_message", e.getMessage());
		}
	}		
	@RequestMapping("selectByadmin.do")
	public ModelAndView selectByadmin(String memberId){
		ModelAndView mv = null;
		try{
		
		
		ArrayList<RoomDTO> rlist = service.searchMyRoomListByMemberId(memberId);			
		System.out.println("myroomlist : "+rlist);
		ArrayList<HashMap> list = new ArrayList<HashMap>();
		for(RoomDTO rdto : rlist){
			HashMap map = new HashMap();
			FileListDTO fdto = service.searchRoomFileByRoomNo(rdto.getRoomNo());
			map.put("rdto", rdto);
			map.put("fdto", fdto);
			list.add(map);				
		}
			return new ModelAndView("roomListByadmin.sub","list", list);
		}catch(SQLException e){
			e.printStackTrace();
			return new ModelAndView("error.res","error_message",e.getMessage());
		}	
	}
	//파일 삭제하는 메소드
	//파일 삭제할때 쿼리문으로 해야하니까 천천히 
		@RequestMapping("deleteFile.do")
		public ModelAndView deletePicture(HttpServletRequest request, HttpSession session)throws Exception{
			ModelAndView mv = null;
			String filename = request.getParameter("filename");	
			int roomNo = Integer.parseInt(request.getParameter("roomNo"));
			service.deleteFile(filename);
			try{
				ArrayList<FileListDTO> flist = service.searchFileListByRoomNo(roomNo);
				return new ModelAndView("modify_room_info_fileup.jsp", "flist", flist);
				
				
			}catch(Exception e){
				e.printStackTrace();
				mv = new ModelAndView("error.res", "error_message", e.getMessage());
			}
			return mv;
		}
			
	@RequestMapping("selectByDong.do")
	public ModelAndView selectByDong(HttpServletRequest request, HttpServletResponse response){
		ModelAndView mv = null;
		try{
		String dong = request.getParameter("dong");
		String search = request.getParameter("search");
		System.out.println(search + dong);
		if(search.equals("sido")){
			System.out.println("도시로 검색합니다.");
			ArrayList<RoomDTO> rlist  = service.selectByCity(dong);
			ArrayList<HashMap> list = new ArrayList<HashMap>();
			for(RoomDTO rdto : rlist){
				HashMap map = new HashMap();
				FileListDTO fdto = service.searchRoomFileByRoomNo(rdto.getRoomNo());
				map.put("rdto", rdto);
				map.put("fdto", fdto);
				map.put("search", search);
				list.add(map);				
			}		
			return new ModelAndView("roomListBydong.room_search","list", list);
			
		}
		if(search.equals("gugun")){
			System.out.println("구로 검색합니다.");
			ArrayList<RoomDTO> rlist  = service.selectBygugun(dong);
			ArrayList<HashMap> list = new ArrayList<HashMap>();
			for(RoomDTO rdto : rlist){
				HashMap map = new HashMap();
				FileListDTO fdto = service.searchRoomFileByRoomNo(rdto.getRoomNo());
				map.put("rdto", rdto);
				map.put("fdto", fdto);
				map.put("search", search);
				list.add(map);				
			}		
			return new ModelAndView("roomListBydong.room_search","list", list);
		}
		if(search.equals("dong")){
			System.out.println("동으로 검색합니다.");
			ArrayList<RoomDTO> rlist  = service.selectByDong(dong);
			ArrayList<HashMap> list = new ArrayList<HashMap>();
			for(RoomDTO rdto : rlist){
				HashMap map = new HashMap();
				FileListDTO fdto = service.searchRoomFileByRoomNo(rdto.getRoomNo());
				map.put("rdto", rdto);
				map.put("fdto", fdto);
				map.put("search", search);
				list.add(map);				
			}		
			return new ModelAndView("roomListBydong.room_search","list", list);
		}
		
		
	}catch(Exception e){
		e.printStackTrace();
		mv = new ModelAndView("error.res", "error_message", e.getMessage());
	}
		return mv;
	}
	@RequestMapping("/randomImage.do")
	public ModelAndView randomImage(){
		ModelAndView mv = null;
		try{
		String img = service.randomImage();
		FileListDTO fdto = new FileListDTO();
		int member = Integer.parseInt(service.countmember());
		int room = Integer.parseInt(service.countroom());
		fdto.setFileName(img);
		System.out.println(img);
		HashMap map = new HashMap();
		map.put("fdto", fdto);
		map.put("member", member);
		map.put("room", room);
		
	
		return new ModelAndView("main.jsp","map",map);
	}catch(Exception e){
		e.printStackTrace();
		mv = new ModelAndView("error.res", "error_message", e.getMessage());
	}
		return mv;
	}


}
	